package edu.sias.hyznxfapi.chat.imageCom;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 图片理解
 */
public class BigModelNew extends WebSocketListener {
    public static final String hostUrl = "https://spark-api.cn-huabei-1.xf-yun.com/v2.1/image";
    public static final String appid = "2a5e4151";
    public static final String apiSecret = "ZjliYzA2OWRlMWU1NzY5M2Y1NzhjOTY3";
    public static final String apiKey = "c2645cc70900a13842bacb151089d9ee";

    public static List<RoleContent> historyList = new ArrayList<>();
    public static String totalAnswer = "";
    public static String newQuestion = "";
    public static Boolean imageAddFlag = false;
    public static String imageUrl = "";
    public static final Gson gson = new Gson();
    private String userId;
    private Boolean wsCloseFlag;

    private static Boolean totalFlag = true;

    private int resultFlase;

    public BigModelNew(String userId, Boolean wsCloseFlag) {
        this.userId = userId;
        this.wsCloseFlag = wsCloseFlag;
    }

    public String getApiResult(String question, String imgUrl) throws Exception {
        totalAnswer = "";
        totalFlag = false;
        imageUrl = imgUrl;
        newQuestion = question;

        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.toString().replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();

        WebSocket webSocket = client.newWebSocket(request, this);

        while (!totalFlag) {
            Thread.sleep(200);
        }
        if (resultFlase != 0){
            //后端挂了，返回错误
            return "服务器出小差了，请刷新页面后再次尝试!";
        }else {
            return totalAnswer;
        }
//        return totalAnswer;
    }

    public static void main(String[] args) throws Exception {
        String apiResult = new BigModelNew("", false).getApiResult("请问，这张图片上有什么东西吗", "F:/E/比赛/软件杯/A05-基于讯飞人工智能平台数智化教育应用软件开发/xf-5/api/图片理解/08.讯飞大模型DEMO/src/main/resources/2.png");
        System.out.println("结果：：：" + apiResult);
    }

    public static boolean canAddHistory() {
        int historyLength = 0;
        for (RoleContent temp : historyList) {
            historyLength += temp.content.length();
        }
        if (historyLength > 12000) {
            historyList.remove(0);
            return false;
        } else {
            return true;
        }
    }

    class MyThread extends Thread {
        private WebSocket webSocket;

        public MyThread(WebSocket webSocket) {
            this.webSocket = webSocket;
        }

        public void run() {
            try {
                JSONObject requestJson = new JSONObject();
                JSONObject header = new JSONObject();
                header.put("app_id", appid);
                header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                JSONObject parameter = new JSONObject();
                JSONObject chat = new JSONObject();
                chat.put("domain", "image");
                chat.put("temperature", 0.5);
                chat.put("max_tokens", 4096);
                chat.put("auditing", "default");
                parameter.put("chat", chat);

                JSONObject payload = new JSONObject();
                JSONObject message = new JSONObject();
                JSONArray text = new JSONArray();

                if (historyList.size() > 0) {
                    for (RoleContent tempRoleContent : historyList) {
                        if (tempRoleContent.content_type.equals("image")) {
                            text.add(JSON.toJSON(tempRoleContent));
                            imageAddFlag = true;
                        }
                    }
                }
                if (historyList.size() > 0) {
                    for (RoleContent tempRoleContent : historyList) {
                        if (!tempRoleContent.content_type.equals("image")) {
                            text.add(JSON.toJSON(tempRoleContent));
                        }
                    }
                }

                RoleContent roleContent = new RoleContent();
                if (!imageAddFlag) {
                    roleContent.role = "user";
                    roleContent.content = Base64.getEncoder().encodeToString(ImageUtil.read(imageUrl));
                    roleContent.content_type = "image";
                    text.add(JSON.toJSON(roleContent));
                    historyList.add(roleContent);
                }

                RoleContent roleContent1 = new RoleContent();
                roleContent1.role = "user";
                roleContent1.content = newQuestion;
                roleContent1.content_type = "text";
                text.add(JSON.toJSON(roleContent1));
                historyList.add(roleContent1);

                message.put("text", text);
                payload.put("message", message);

                requestJson.put("header", header);
                requestJson.put("parameter", parameter);
                requestJson.put("payload", payload);

                webSocket.send(requestJson.toString());

                while (!wsCloseFlag) {
                    Thread.sleep(200);
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onOpen(WebSocket webSocket, Response response) {
        super.onOpen(webSocket, response);
        MyThread myThread = new MyThread(webSocket);
        myThread.start();
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
            System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
            webSocket.close(1000, "");
            totalFlag = true;
            resultFlase = myJsonParse.header.code;
            return;
        }

        List<Text> textList = myJsonParse.payload.choices.text;
        for (Text temp : textList) {
            totalAnswer += temp.content;
        }

        if (myJsonParse.header.status == 2) {
            if (canAddHistory()) {
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                roleContent.setContent_type("text");
                historyList.add(roleContent);
            } else {
                historyList.remove(0);
                RoleContent roleContent = new RoleContent();
                roleContent.setRole("assistant");
                roleContent.setContent(totalAnswer);
                roleContent.setContent_type("text");
                historyList.add(roleContent);
            }
            wsCloseFlag = true;
            totalFlag = true;
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        super.onFailure(webSocket, t, response);
        try {
            if (response != null) {
                int code = response.code();
                System.out.println("onFailure code:" + code);
                System.out.println("onFailure body:" + response.body().string());
                if (code != 101) {
                    System.out.println("connection failed");
                    System.exit(0);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        totalFlag = true;
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", sha);
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();
        return httpUrl.toString();
    }

    class JsonParse {
        Header header;
        Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        Choices choices;
    }

    class Choices {
        List<Text> text;
    }

    class Text {
        String role;
        String content;
    }

    class RoleContent {
        String role;
        String content;
        String content_type;

        public String getContent_type() {
            return content_type;
        }
        public void setContent_type(String content_type) {
            this.content_type = content_type;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}
